package com.i2bt.app.login.model;

import org.json.JSONException;
import org.json.JSONObject;

import com.i2bt.app.BaseActivity;
import com.i2bt.app.BaseJsonModel;
import com.i2bt.app.login.LoginActivity;
import com.i2bt.app.main.MainActivity;
import com.i2bt.bean.LoginBean;
import com.i2bt.common.AndroidRestContract;
import com.i2bt.common.UserConfig;

public class LoginJsonHandle extends BaseJsonModel {
	LoginActivity act;

	public LoginJsonHandle(BaseActivity activity) {
		super(activity);
		act = (LoginActivity) this.activity;
	}

	@Override
	protected String logicToWrap() {
		// TODO Auto-generated method stub
		LoginBean bean = (LoginBean) this.beanParam;
		try {
			jsonParam.put(AndroidRestContract.ACTION, bean.getAct());
			jsonParam.put(AndroidRestContract.USER_ID, bean.getUserId());
			jsonParam.put(AndroidRestContract.PASSWORD, bean.getPassword());
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return jsonParam.toString();
	}

	@Override
	protected void logicToUnwrap(boolean isSuc, String result) {
		// TODO Auto-generated method stub
		System.out.println(result);
		if (isSuc) {
			try {
				JSONObject ja = new JSONObject(result);
				boolean succ = ja.getBoolean(AndroidRestContract.SUCCEED);
				String mes = null;
				if (succ) {
					mes = ja.getString(AndroidRestContract.TOKEN);
					UserConfig.token = mes;

					mes = ja.getString(AndroidRestContract.NICK_NAME);
					UserConfig.userName = mes;

					wirteLoginHistory(act.getUserNameStr(),
							act.getPasswordStr());
					this.act.goActivityAndFinish(MainActivity.class);
				} else {
					mes = ja.getString(AndroidRestContract.MESSAGE);
					act.showWarnToast(succ + mes);
				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} else {
			act.showWarnToast("网络连接失败");
		}
	}

	/**
	 * 登陆成功，将登陆信息写入本地记录，下次不需要重新输入登陆
	 * 
	 * @param userId
	 *            用户Id
	 * @param password
	 *            用户密码
	 */
	public void wirteLoginHistory(String userId, String password) {
		this.activity.writeXML("ACCOUNT", "USERID", userId);
		this.activity.writeXML("ACCOUNT", "PASSWORD", password);
		UserConfig.userId = userId;
		UserConfig.password = password;
	}
}
